<template>
  <div class="insideWarehouse-wrap">
    <div class="insideWarehouse-content" :style="{height:pageHeight + 'px'}">
      <div class="left-search">
        <el-form inline label-width="80px" >
          <el-form-item :label="$t('config.wareName')">
            <el-input v-model="search.whsename" disabled></el-input>
          </el-form-item>
          <el-form-item :label="$t('config.areaName')">
            <el-input v-model="search.areakey" disabled></el-input>
          </el-form-item>
          <el-form-item :label="$t('config.putZoneName')" required>
            <el-select v-model="search.putawayzonename" :placeholder="$t('common.select')"  filterable clearable @change="getWhseInfo">
              <el-option v-for="opt in putawayList" :key="opt.code" :label="opt.description" :value="opt.description"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table :data="shelfList" @selection-change="handleSelectionChange">
          <el-table-column :label="$t('app.index')" type="index" width="50"></el-table-column>
          <el-table-column type="selection" width="50"> </el-table-column>
          <el-table-column :label="$t('config.shelfRowNo')" prop="keyName"> </el-table-column>
        </el-table>
      </div>
      <div class="right-content">
        <el-form inline label-width="80px">
          <el-form-item :label="$t('config.lineType')">
              <el-select v-model="plan.lineType" :placeholder="$t('common.select')" clearable>
                <el-option v-for="opt in options.LineType" :key="opt.code" :label="opt.description" :value="opt.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('config.horOrder')">
            <el-select v-model="plan.horizontalOrder" :placeholder="$t('common.select')" @change="indexCreate">
              <el-option v-for="opt in options.HorizontalOrder" :key="opt.code" :label="opt.description" :value="opt.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('config.verOrder')">
            <el-select v-model="plan.verticalOrder" :placeholder="$t('common.select')" @change="indexCreate">
              <el-option v-for="opt in options.VerticalOrder" :key="opt.code" :label="opt.description" :value="opt.code"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="loc-list-content" :style="{height:pageHeight + 'px'}">
          <div v-for="(loc,rowName) in locInfo" :key="rowName" class="loc-list-row">
            <p class="loc-list-name">{{$t('config.rowNo')}}：{{selectionShelfList.find(item => item.key == rowName)?.keyName}}</p>
            <div class="cell-wrap">
              <span class="divier-top">{{$t('config.top')}}</span>
              <span class="divier-bottom">{{$t('config.bottom')}}</span>
              <template v-for="(column,colIndex) in loc">
                  <div class="loc-list-column">
                    <template v-for="(layer,layIndex) in column">
                      <div class="loc-list-layer">{{layer.loc}}<div class="loc-list-index">{{getIndex(layer.loc)}}</div></div>
                    </template>
                  </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="insideWarehouse-footer" v-show="orderList.length > 0">
      <!-- <el-button>{{$t("common.cancel")}}</el-button> -->
      <el-button type="primary" :disabled="!this.btnPermNameList.includes('WM03180101')" @click="handleSubmit">{{$t("common.save")}}</el-button>
    </div>
  </div>
</template>

<script>
import baseMixin from "@/mixins/BaseMixin";
export default {
  mixins: [baseMixin],
  name:"insideWarehouse",
  data(){
    return {
      search:{
        whsename:"",
        areakey:"",
        putawayzonename:""
      },
      shelfList:[],//货架列表
      selectionShelfList:[],
      rowList:[],//库位信息,排数组
      locInfo:{},//库位信息,排列层数组
      orderList:[],//按序号排列的库位信息
      plan:{
        lineType:'11401',
        verticalOrder:"",
        horizontalOrder:"",
        // verticalOrder:'11301',//纵向顺序
        // horizontalOrder:'11201'//横向顺序
      },
      putawayList:[],
      options:{
        LineType:[],
        VerticalOrder:[],
        HorizontalOrder:[]
      },
      pageHeight:600
    }
  },
  methods:{
    handleSubmit(){
      const lineType = this.plan.lineType;
      if(lineType == '11401'){
        //上架线路
        this.orderList.forEach(item => item.put_shelves_number = item.shelves_number)
      }else if(lineType == '11402'){
        //拣货线路
        this.orderList.forEach(item => item.pick_shelves_number = item.shelves_number)
      }else{
        return this.$message(this.$selectPlease("config.lineType"))
      }
      this.$api.post('/upDateLocs',this.orderList).then(res => {
          this.getShelfList()
          const type = lineType == '11401' ? this.$t('config.putShelves') :  this.$t('config.pickShelves');
          this.$message.success(type + this.$t('app.upMes') )
      })
    },
    getIndex(loc){
      if(this.orderList.length > 0){
        return this.orderList.find(item => item.loc === loc)?.shelves_number
      }
      const key = this.plan.lineType == '11401' ? 'put_shelves_number' : this.plan.lineType == '11402' ? 'pick_shelves_number' : '';
      return key ? this.rowList.find(item => item.loc === loc)[key] : '';
    },
    //生成序号
    indexCreate(){
      const {horizontalOrder,verticalOrder} = this.plan;
      let locInfo =this. _.cloneDeep(this.locInfo);
      if(horizontalOrder == ""||verticalOrder == ""){
        this.orderList = []
        return
      }
      if(horizontalOrder == '11201'){
        //从左到右
        
      }else if(horizontalOrder == '11202'){
        //从右到左
        Object.keys(locInfo).forEach(key => {
          locInfo[key].reverse()
        })
      }
      if(verticalOrder == '11301'){
        //  从下到上
        Object.keys(locInfo).forEach(key => {
          locInfo[key].forEach(colunm => {
            colunm.reverse()
          })
        })
      }else if(verticalOrder == '11302'){
        //  从上到下
      }else if(verticalOrder == '11303'){
        //  从下到上，上下交替
        Object.keys(locInfo).forEach(key => {
          locInfo[key].forEach((colunm,colIndex) => {
            if(colIndex%2 === 0){
              colunm.reverse()
            }
          })
        })
      }else if(verticalOrder == '11304'){
        //  从上到下，上下交替
        Object.keys(locInfo).forEach(key => {
          locInfo[key].forEach((colunm,colIndex) => {
            if(colIndex%2 !== 0){
              colunm.reverse()
            }
          })
        })
      }
      let total = 0,orderList = [];
      Object.keys(locInfo).forEach(key => {
        const row = locInfo[key]
        for (let r = 0; r < row.length; r++) {
          const column = row[r];
          for (let c = 0; c < column.length; c++) {
            const layer = column[c];
            total++
            layer.shelves_number = this._.padStart(total.toString(),3,'0');
            orderList.push(layer)
          }
        }
      })
      this.orderList = orderList
    },
    handleSelectionChange(val){
      this.selectionShelfList = val;
      if(val&&val.length > 0){
        const params = val.map(loc => loc.key);
        this.$api.post('/queryLocByKey',params).then(res => {
            const data = res.data;
            let dataList = {};
            this.rowList = [];
            Object.keys(data).forEach(key=> {
              const rowData = data[key];
              this.rowList = this.rowList.concat(rowData);
              const min_column = this._.minBy(rowData,'column_no').column_no;
              const max_column = this._.maxBy(rowData,'column_no').column_no;
              const min_layer = this._.minBy(rowData,'layer_no').layer_no;
              const max_layer = this._.maxBy(rowData,'layer_no').layer_no;
              if(min_column === 0&&max_column === 0&&min_layer === 0&&max_layer === 0){
                const keyName = val.find(item => item.key == key)?.keyName
                  this.$message(`${keyName}`)
              }else{
                if(max_column - min_column >= 0&&max_layer - min_layer >= 0){
                  dataList[key] = []
                  for (let c = 0; c <= max_column - min_column; c++) {
                    dataList[key][c] = []
                    for (let l = 0; l <= max_layer - min_layer; l++) {
                      dataList[key][c][l] = rowData.find(row => row.column_no == c + min_column&&row.layer_no == l + min_layer)
                    }
                    dataList[key][c].reverse()
                  }
                }else{
                  const keyName = val.find(item => item.key == key)?.keyName
                  this.$message(`${keyName}`)
                }
              }
            })
            this.locInfo = dataList;
            this.indexCreate()
        })
      }else{
        this.locInfo = {};
        this.orderList = []
      }
    },
    getWhseInfo(putawayzonename){
      this.$api.get(`/rtxLocList/queryPutawayzoneByName/${putawayzonename}`).then(res => {
          if(res.data.list.length > 0){
            const data = res.data.list[0];
            this.search.whsename = data.whsename;
            this.search.areakey = data.areakey;
            this.getShelfList()
          }else{
            this.search.whsename = '';
            this.search.areakey = '';
            this.$message.info(this.$inputEmptyMes('security.wareHouse'))
          }
        
      })
    },
    getShelfList(){
      this.shelfList = []
      const putawayzonename = this.search.putawayzonename;
      this.$api.post(`/fuzzyQueryLocByAreaNumberOrName/${putawayzonename}`).then(res => {
          const data = res.data.data;
          this.shelfList = []
          if(data&&Array.isArray(data)&&data.length > 0){
            this.shelfList = data
          }else{
            this.$message.info(this.$inputEmptyMes('config.shelf'))
          }
      })
    },
    async getOptions(){
      try {
        const res = await this.$api.post("/rtxLocList/querycodeLkupByList",Object.keys(this.options))
          const data = res.data.list;
          data.forEach(item => {
            this.options[item.codelkupName] = item.codelkupList
          })
      } catch (error) {
        this.$message.error(error)
      }
      try {
        const res = await this.$api.get("/queryPutawayzoneDropDown")
          this.putawayList = res.data
        
      } catch (error) {
        this.$message.error(error)
      }
    }
  },
  mounted(){
    this.pageHeight = this.getHeight(window,20);
    this.getOptions()
  }
}
</script>

<style lang="scss" scoped>
.insideWarehouse-content{
  overflow: hidden;
  .left-search{
    float: left;
    width: 300px;
    height: 100%;
    border-right: 1px solid #ddd;
  }
  .right-content{
    overflow: hidden;
  }
  .el-form-item{
    vertical-align: middle;
    ::v-deep .el-form-item__content{
      vertical-align: middle;
    }
    .el-input,.el-select{
      width: 140px;
    }
  }
  .loc-list-content{
    border-top: 1px solid #ddd;
    padding: 10px;
    padding-bottom: 80px;
    overflow-y: auto;
    .loc-list-row{
      position: relative;
      margin-bottom: 20px;
      .loc-list-name{
        color: #409eff;
      }
      .cell-wrap{
        border: 1px solid #ddd;
        padding: 10px;
        overflow-x: auto;
        overflow-y: hidden;
        display: flex;
        flex-wrap: nowrap;
        align-items: flex-start;
        align-content: flex-start;
        z-index: 8;
        &::before{
          content: '左';
          padding: 1em 0;
          position: absolute;
          left: 0;
          top: calc(50% - 1em);
          background: #fff;
        pointer-events: none;
      }
        &::after{
          content: '右';
          padding: 1em 0;
          position: absolute;
          right: 0;
          top: calc(50% - 1em);
          background: #fff;
        pointer-events: none
      }
      }
      .divier-top,.divier-bottom{
        position: absolute;
        left: 50%;
        z-index: 9;
        padding: 0 1em;
        pointer-events: none
      }
      .divier-top{
        top: 2em;
      }
      .divier-bottom{
        bottom: -1.5em;
      }
      .loc-list-column{
        width: 240px;
        margin: 10px;
      }
      .loc-list-layer{
        line-height: 3.6em;
        border: 1px solid #ddd;
        width: 200px;
        margin-bottom: 10px;
        text-align: center;
        font-size: 13px;
        font-weight: 600;
        &:last-child{
          margin: 0;
        }
      }
      .loc-list-index{
        color: #409eff;
        padding: 0 0.8em;
        font-size: 14px;
        font-weight: 600;
        float: right;
        border-left: 1px solid #ddd;
      }
    }
  }
}
.insideWarehouse-footer{
  margin-top: 10px;
  padding: 15px 0;
  background: #f1f2f3;
  text-align: center;
}
</style>